<?php
// Make sure we don't expose any info if called directly
if ( basename( $_SERVER['PHP_SELF'] ) == basename( __FILE__ ) ) {
	die( 'Sorry, but you cannot access this page directly.' );
}

add_action('admin_menu', 'site_basic_page_images');
function site_basic_page_images() {
	add_submenu_page('site-basic-setting', '网站图片复用', '网站图片复用', 'manage_options', 'site-basic-images', 'site_basic_image_page' );
}

// Retrieves plugin options if they exist or returns default values if not

function basic_getimages() {
	// delete_option('basic_images');
	if( get_option( 'basic_images' )) {
		$basic_images = get_option( 'basic_images' );
	} else {
		$basic_images = '';
	}
	return $basic_images;
}

function site_basic_image_page() {
?>
	<div class="wrap">
		<?php settings_errors(); ?>
		<div class="custom_option">
			<form method="post" action="options.php"  class="basic-form-setting">
				<?php
					settings_fields('basic_image_url');
					basic_image_function_area();
				?>
				<table class="codes-section">
					<thead>
						<tr class="code-section">
							<th>Label</th>
							<th>Key</th>
							<th></th>
							<th>图片</th>
							<th>更新</th>
							<th>删除</th>
						</tr>
					</thead>
					<tbody>
						<?php
							$basic_getimages = basic_getimages();
							if ($basic_getimages) {
								$basic_items = array();
								for($i=0; $i<ceil(count($basic_getimages)); $i++) {
									$basic_items[] = array_slice($basic_getimages, $i * 3, 3);
								}
								foreach ($basic_items as $basic_item) {
									if ($basic_item) {
										echo '<tr class="code-section">';
										foreach ($basic_item as $basic_info => $value) {
											if (strpos($basic_info, 'basiclabel')) {
												echo '<td><input class="form-label" required name="basic_images['.$basic_info.']" value="'.$basic_item[$basic_info].'" placeholder="Label" /></td>';
											}
											if (strpos($basic_info, 'basickey')) {
												echo '<td><input class="form-key" required name="basic_images['.$basic_info.']" value="'.$basic_item[$basic_info].'" placeholder="Key" /></td>';
											}
											if (strpos($basic_info, 'basicimage')) {
												echo '<td><input class="'.$basic_info.'-image form-image" required name="basic_images['.$basic_info.']" value="'.$basic_item[$basic_info].'" type="hidden" /></td>';
												echo '<td><img class="'.$basic_info.'-preview" src="'.$basic_item[$basic_info].'"></td>';
												echo '<td><button type="button" class="update btn-default" data-class="'.$basic_info.'">更新</button></td>';
											}
										}
										echo '<td><button type="button" class="delete btn-default">删除</button></td>';
										echo '</tr>';
									}
								}
							}
						?>
					</tbody>
				</table>
				<hr>
				<button type="button" id="add-code">增加</button>
				<button type="submit" name="submit">保存设置</button>
			</form>
		</div>
	</div>
<?php }

add_action( 'admin_init', 'basic_register_images' );

function basic_register_images(){

	register_setting( 'basic_image_url', 'basic_images' );

}

function basic_image_function_area(){?>
	<style>
		.form-label{
			background: transparent;
			border: 1px solid transparent;
			width: 160px;
			font-weight: bold;
		}
		.btn-default{
			background: blue;
			border: 1px solid blue;
			color: #fff;
			padding: 0 15px;
			line-height: 28px;
			margin: 0 5px;
			border-radius: 5px;
			-webkit-border-radius: 5px;
			-moz-border-radius: 5px;
			cursor: pointer;
		}
		.code-section th{
			text-align: center;
			padding: 0 0 10px;
		}
		.codes-section td{
			padding: 5px;
		}
		.code-section img{
			max-width: 80px;
			margin: 0 20px;
		}
	</style>
	<h2>网站图片复用</h2>
	<p class="description">指定图片功能，并可以用shortcode调用，调用方法为<code>[basic_image key="$key"]</code>或<code>[basic_image key="$key" output="image"]</code></p>
	<p>主要目的是用于：自定义post type的archive页面或者分类页面调用图片。Key必须唯一。</p>
	<script>
		jQuery(document).ready(function($) {
			init();
			deleteItem();
			imageUpdate();
			$("#add-code").click(function() {
				$(".codes-section tbody").append('<tr class="code-section">' +
				'<td><input class="form-label" value="" placeholder="Label" required /></td>' +
				'<td><input class="form-key" value="" placeholder="Key" required /></td>' +
				'<td><input class="form-image" value="<?php echo plugins_url('images/demo.png' , __FILE__ );?>" placeholder="Image" type="hidden" required /></td>' +
				'<td><img alt="" src="<?php echo plugins_url('images/demo.png' , __FILE__ );?>" /></td>' +
				'<td><button type="button" class="update btn-default">更新</button></td>' +
				'<td><button type="button" class="delete btn-default">删除</button></td>' +
				'</tr>' );
				init();
				deleteItem();
				imageUpdate();
			});
		})

		function init() {
			$(".form-key").on("change", function() {
				$(this).attr("name", "basic_images[mybasickey-" + $(this).val() + "]");
				$(this).closest(".code-section").find(".update").data("class", "mybasicimage-" + $(this).val());
				$(this).closest(".code-section").find("img").addClass("mybasicimage-" + $(this).val() + "-preview");
				$(this).closest(".code-section").find(".form-label").attr("name", "basic_images[mybasiclabel-" + $(this).val() + "]");
				$(this).closest(".code-section").find(".form-image").attr("name", "basic_images[mybasicimage-" + $(this).val() + "]").addClass("mybasicimage-" + $(this).val() + "-image");
			});
		}

		function deleteItem() {
			$(".delete").on("click", function() {
				$(this).closest(".code-section").html('');
			});
		}

		function imageUpdate() {
			$('.update').click(function(e){
				e.preventDefault();
				var active_key = $(this).closest(".code-section").find(".form-key").val();
				if (active_key) {
					var active_class = $(this).data("class");
					var image_uploader = wp.media({
						title: 'Select or upload an image',
						button: { text: 'Select It' },
						multiple: false
					}).on('select', function(){
						var attachment = image_uploader.state().get('selection').first().toJSON();
						// 通过.length 判断元素是否存在
						if ($('.' + active_class + '-image').length > 0) {
							$('.' + active_class + '-image').val(attachment.url);
						}
						if ($('.' + active_class + '-preview').length > 0) {
							$('.' + active_class + '-preview').attr("src", attachment.url);
						}
					}).open();
				} else {
					alert('Key 不能为空');
				}

			});
		}
	</script>
<?php }

function basic_shortcode_function($atts) {
	$attr = shortcode_atts( array(
		'key' => '',
		'output' => ''
	), $atts );

	if($attr["key"]){
		$basic_get_url = basic_getimages('mybasicimage-'.$attr["key"]);
		if ($basic_get_url) {
			$basic_get_image = '<img src="'.$basic_get_url.'" alt="" />';
			if($attr["output"] == 'image'){
				return $basic_get_image;
			} else {
				return $basic_get_url;
			}
		} else {
			return '巧妇难为无米之炊。';
		}
	} else {
		return '请检查你的shortcode格式和参数是否正确。';
	}

}
add_shortcode( 'basic_image', 'basic_shortcode_function' );